package com.vast.admin.controller;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vast.admin.annotation.PassToken;
import com.vast.admin.annotation.UseToken;
import com.vast.admin.entity.*;
import com.vast.admin.entity.dto.ContractDatumAppDto;
import com.vast.admin.entity.dto.ContractDetailDto;
import com.vast.admin.entity.dto.ContractDto;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.service.*;
import com.vast.admin.service.impl.ApplyManagersService;
import com.vast.admin.service.impl.CompanyAccountService;
import com.vast.admin.service.impl.CompanyService;
import com.vast.admin.service.impl.ContractDatumService;
import com.vast.common.annotation.Log;
import com.vast.common.constant.MessageCode;
import com.vast.common.core.domain.Result;
import com.vast.common.core.domain.entity.SysRole;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.utils.FileUtils;
import com.vast.common.utils.SecurityUtils;
import com.vast.framework.web.service.SysLoginService;
import com.vast.framework.web.service.TokenService;
import com.vast.system.domain.SysUserRole;
import com.vast.system.service.ISysRoleService;
import com.vast.system.service.ISysUserRoleService;
import com.vast.system.service.ISysUserService;
import com.vast.system.shiro.ShiroUtils;
import com.vast.system.utils.Constant;
import com.vast.system.utils.IPUtils;
import com.vast.system.utils.OssUtils;
import com.vast.system.utils.StringUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * App相关接口 前端控制器
 * </p>
 *
 * @author zhaohao
 * @since 2018-10-24
 */
@RestController
@Api(value = "APP相关的api", tags = { "APP服务模块" })
@RequestMapping("/app")
public class AppController {


//	@Autowired
//	private SysLogService sysLogService;

	@Autowired
	private ISysUserService userService;

	@Autowired
	private TempleteService templeteService;

	@Autowired
	private PlaceholderService placeholderService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ContractService contractService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private ContractDetailService contractDetailService;

	@Autowired
	private BannerService bannerService;

	@Autowired
	private ApplyManagersService applyManagersService;

	@Autowired
	private ISysUserRoleService managerRoleService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
    private CompanyAccountService companyAccountService;

	@Autowired
	private OssUtils ossUtils;

	@Autowired
	private ContractDatumService contractDatumService;

	@Autowired
	private ApplyMsgUserService applyMsgUserService;

	@Autowired
	private SysLoginService loginService;

	@Autowired
	private TokenService tokenService;

	// 登录
	@ApiOperation(value = "用户登录接口", notes = "根据用户名,密码登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query", defaultValue = "13419519796"),
			@ApiImplicitParam(name = "pwd", value = "用户密码", required = true, dataType = "String", paramType = "query", defaultValue = "123456"),
			})
	@PostMapping("/login")
	@PassToken
	public Result<SysUser> login(String username, String pwd) {

		if(StringUtils.isEmpty(username)){
			return new Result<>(MessageCode.PARAM_ERROR, "账号不能为空");
		}

		if(StringUtils.isEmpty(pwd)){
			return new Result<>(MessageCode.PARAM_ERROR, "密码不能为空");
		}

		if("0".equals(userService.checkUserNameUnique(username))){
			return new Result<>(MessageCode.ERROR, "账号不存在");
		}

//		Subject subject = ShiroUtils.getSubject();
//		UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
//		subject.login(token);

		String token = loginService.loginByUsernameAndPassword(username, pwd);
		SysUser manager = tokenService.getLoginUser(token).getUser();
		manager.setToken(token);
//		SysUser manager = (SysUser) subject.getPrincipal();
//		manager.setToken(JWTUtil.sign(manager.getUserId() + "", manager.getPassword()));

		List<SysUserRole> managerRoles = managerRoleService.list(new QueryWrapper<SysUserRole>().eq(SysUserRole.COL_MANAGER_ID,manager.getUserId()));
		List<Long> roleIds = new ArrayList<>();
		for (SysUserRole managerRole : managerRoles) {
			roleIds.add(managerRole.getRoleId());
		}
		Long[] roleIdArr = new Long[roleIds.size()];
		roleIds.toArray(roleIdArr);
		manager.setRoleIdList(roleIdArr);

		if(!manager.isHasRole(Constant.SUPER_ADMIN)){//超级管理员
			if(manager.getCompanyId() != null && manager.getCompanyId() > 0){
				Company company = companyService.getById(manager.getCompanyId());
				if(company != null){
					manager.setCompanyName(company.getName());
				}
			}

//			QueryWrapper<ManagerRole> managerRoleQueryWrapper = new QueryWrapper<>();
//			managerRoleQueryWrapper.eq(ManagerRole.COL_MANAGER_ID, manager.getUserId());
//			List<ManagerRole> managerRoles = managerRoleService.list(managerRoleQueryWrapper);
			boolean isCompanyAdmin = false;
			if(managerRoles!= null && !managerRoles.isEmpty()){
//				List<Long> roleIds = new ArrayList<>();
//				for (ManagerRole managerRole : managerRoles) {
//					roleIds.add(managerRole.getRoleId());
//				}
				List<SysRole> roleList = (List<SysRole>) roleService.listByIds(roleIds);
				if(roleList!= null && !roleList.isEmpty()){
					for (SysRole role : roleList) {
						//如果是企业管理员
						manager.setRoleNames(role.getRoleName());
						if(Constant.COMPANY_ADMIN_ALIAS.equals(role.getRoleKey())){
							isCompanyAdmin = true;
							break;
						}
					}
				}
			}
			if(isCompanyAdmin){
				QueryWrapper<CompanyAccount> companyAccountQueryWrapper = new QueryWrapper<>();
				companyAccountQueryWrapper.eq(CompanyAccount.COL_COMPANY_ID,manager.getCompanyId());
				CompanyAccount companyAccount = companyAccountService.getOne(companyAccountQueryWrapper);
				if(companyAccount!= null){
					DecimalFormat df = new DecimalFormat("0.00");
					manager.setAccountMoney(df.format(companyAccount.getMoney()));
				}else{
					manager.setAccountMoney("0.00");
				}
			}else{

			}

		}else{
			manager.setCompanyName("系统管理");
		}




		//保存登录日志
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		SysLog sysLog = new SysLog();
		sysLog.setUsername(manager.getNickName());
		sysLog.setMethod( request.getMethod());
		sysLog.setOperation("app登录");
		sysLog.setCreateTime(DateTime.now());
		sysLog.setValid(1);
		//获取用户ip地址
		sysLog.setIp(IPUtils.getIpAddr(request));
		sysLog.setUrl(request.getRequestURL().toString());
		sysLog.setValid(1);
		sysLog.setType(1); //登录日志
		sysLog.setStatus(1);
//		sysLogService.save(sysLog);

		return new Result<SysUser>(MessageCode.SUCCESS, "登录成功",manager);
	}




	// 退出
	@ApiOperation(value = "用户注销接口", notes = "根据token注销")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true) })
	@PostMapping("/logout")
	@UseToken
	public Result<Boolean> logout() {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		manager.setToken("");
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String ip = request.getHeader("real-ip");
		SysLog sysLog = new SysLog();
		sysLog.setUsername(manager.getNickName());
		sysLog.setMethod( request.getMethod());
		sysLog.setOperation("退出");
		sysLog.setCreateTime(DateTime.now());
		sysLog.setValid(1);
		//获取用户ip地址
		sysLog.setIp(ip);
		sysLog.setUrl(request.getRequestURL().toString());
		sysLog.setValid(1);
		sysLog.setType(1); //登录日志
		sysLog.setStatus(1);
//		sysLogService.save(sysLog);
		ShiroUtils.logout();
		return new Result<Boolean>(MessageCode.SUCCESS, "退出成功",true);
	}
//
	// 检测手机号是否注册
	@ApiOperation(value = "检测手机号是否注册", notes = "检测手机号是否注册")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", dataType = "String", required = true) })
	@PostMapping("/checkAccount")
	@PassToken
	public Result checkUser(String phone) {
		QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
		userQueryWrapper.eq(SysUser.COL_ACCOUNT, phone);
		SysUser manager = userService.getOne(userQueryWrapper);
		if (manager != null) {
			return new Result(MessageCode.EXIST_USER, "用户已存在");
		}
		return new Result(MessageCode.UNDEFINED_USER, "用户不存在");
	}

	@ApiOperation(value = "查询Banner列表", notes = "查询Banner列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "type", value = "类型", dataType = "int", defaultValue = "1", required = true)
	})
	@PassToken
	@GetMapping("/getBannerList")
	public Result<IPage<Banner>> getBannerList(@ApiParam(hidden = true) Page<Banner> page, Integer type) {
		return new Result<IPage<Banner>>(MessageCode.SUCCESS, "获取成功", bannerService.getBannerList(page,type));
	}

	@ApiOperation(value = "查询合同模版列表", notes = "查询合同模版列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "queryItems", value = "查询条件,json集合", defaultValue = "account,EQ,13419519796;", dataType = "String", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
	})
	@UseToken
	@PreAuthorize("@ss.hasPermi('system:user:list')")
	@GetMapping("/getTemplateList")
	public Result<IPage<Templete>> page(@ApiParam(hidden = true) Page<Templete> page, boolean listMode,String queryItems, String orderField, QueryOrderEnum order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<IPage<Templete>>(MessageCode.SUCCESS, "获取成功", templeteService.queryAppContractTemplateList(manager,page, listMode, queryItems, orderField,order));
	}


	@ApiOperation(value = "根据模版记录id获取模版属性配置字段", notes = "根据模版记录id获取模版属性配置字段")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "id", value = "合同记录模版id", dataType = "Long",  required = true)
	})
	@UseToken
	@GetMapping("/getTemplateFieldsById")
	public Result getTemplateFieldsByTemplateRecordId(Long id) {
		if(id != null) {
			List<Map<String, Object>> templateFields  = placeholderService.getPlaceholderByTempleteRecordId(id);
			if(templateFields != null){
				return new Result(MessageCode.SUCCESS, "获取成功", templateFields);
			}else{
				return new Result(MessageCode.ERROR, "获取失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "根据客户手机号码查询客户", notes = "根据客户手机号码查询客户")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "type", value = "类型:企业方:1:企业方,3:担保方,4:其它企业 ; 2: 客户方", dataType = "int", required = true),
			@ApiImplicitParam(paramType = "query", name = "phone", value = "手机号码", dataType = "String",  required = true)
	})
	@UseToken
	@Log(title = "根据客户手机号码查询客户")
	@GetMapping("/getCustomerByPhone")
	public Result getCustomerByPhone(String phone, Integer type) {
		if(!StringUtils.isEmpty(phone) && type != null) {
			if(type == 2){
				Customer customer = customerService.getCustomerByPhone(phone);
				if(customer != null){
					return new Result(MessageCode.SUCCESS, "获取成功", customer);
				}else{
					return new Result(MessageCode.SUCCESS, "查无此数据");
				}
			}else if(type == 1 || type == 3 || type ==4){
				Company company =companyService.getCompanyByPhone(phone);
				if(company != null){
					return new Result(MessageCode.SUCCESS, "获取成功", company);
				}else{
					return new Result(MessageCode.SUCCESS, "查无此数据");
				}
			}
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "创建合同签署流程", notes = "创建合同签署流程")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDao", value = "合同流程信息", dataType = "ContractDto",  required = true)
	})
	@UseToken
	@Log(title = "创建合同签署流程")
	@PostMapping("/createContract")
	public Result createContract(ContractDto contractDao) {
		if(contractDao != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Long contractId = contractService.createContract(contractDao,manager);
			if(contractId != null){
				return new Result(MessageCode.SUCCESS, "创建成功", contractId);
			}else{
				return new Result(MessageCode.ERROR, "创建失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "添加合同签署流程客户", notes = "添加合同签署流程客户")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDao", value = "合同流程信息", dataType = "ContractDto",  required = true)
	})
	@UseToken
	@Log(title = "添加合同签署流程客户")
	@PostMapping("/addContractCustomer")
	public Result addContractCustomer(ContractDto contractDao) {
		if(contractDao != null && contractDao.getCustomerId() != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Long contractId = contractService.addContractCustomer(contractDao,manager);
			if(contractId != null){
				return new Result(MessageCode.SUCCESS, "添加成功", contractId);
			}else{
				return new Result(MessageCode.ERROR, "添加失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@ApiOperation(value = "保存合同信息", notes = "保存合同信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDetailDto", value = "合同信息", dataType = "ContractDetailDto",  required = true)
	})
	@UseToken
	@Log(title = "保存合同信息")
	@PostMapping("/saveContractDetail")
	public Result saveContractDetail(@RequestBody ContractDetailDto contractDetailDto) {
		if(contractDetailDto != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			boolean flag = contractService.saveContractDetail(contractDetailDto,manager);
			if(flag){
				return new Result(MessageCode.SUCCESS, "保存成功");
			}else{
				return new Result(MessageCode.ERROR, "保存失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同签署流程列表", notes = "获取合同签署流程列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "queryItems", value = "查询条件,json集合", defaultValue = "account,EQ,13419519796;", dataType = "String", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
	})
	@UseToken
	@GetMapping("/getContractList")
	public Result<IPage<Contract>> getContractList(@ApiParam(hidden = true) Page<Contract> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<IPage<Contract>>(MessageCode.SUCCESS, "获取成功", contractService.queryList(manager,page, listMode, queryItems, orderField,order));
	}


	@ApiOperation(value = "锁定并生成合同", notes = "锁定并生成合同")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "id", value = "合同流程ID", dataType = "Long", required = false),
			@ApiImplicitParam(paramType = "query", name = "flag", value = "是否检查签署者（0检查 1忽略）", dataType = "Integer", required = false)
	})
	@UseToken
	@Log(title = "锁定并生成合同")
	@GetMapping("/lockAndProduceContract")
	public Result lockAndProduceContract(Long id, @RequestParam(defaultValue = "0") Integer flag){
		if(id != null && id > 0) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			contractService.productionContract(id, manager, flag);
			return new Result(MessageCode.SUCCESS, "操作成功");
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同签署流程里的合同列表", notes = "获取合同签署流程里的合同列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同流程ID", dataType = "Long", required = false)
	})
	@UseToken
	@GetMapping("/getFlowContractList")
	public Result getFlowContractList(Long contractId){
		if(contractId != null && contractId > 0) {
			List<ContractDetail> result = contractDetailService.getByContractId(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同签署流程里的合同详情", notes = "获取合同签署流程里的合同详情")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = false)
	})
	@UseToken
	@GetMapping("/getContractDetailById")
	public Result getContractDetailById(Long contractId){
		if(contractId != null && contractId > 0) {
			ContractDetailDto result = contractService.getContractDetail(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同预览链接", notes = "获取合同预览链接 注: 合同状态签署中的,即status>=3")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = false)
	})
	@UseToken
	@GetMapping("/getContractPreviewUrl")
	public Result getContractPreviewUrl(Long contractId){
		if(contractId != null && contractId > 0) {
			String result = contractService.getContractPreviewUrl(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@ApiOperation(value = "用户账号申请", notes = "用户账号申请")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "applyManager", value = "用户账号申请", dataType = "ApplyManagers",  required = true)
	})
	@PassToken
	@Log(title = "用户账号申请")
	@PostMapping("/managerApply")
	public Result managerApply(@RequestBody ApplyManagers applyManager) {
		if(applyManager != null && applyManager.getPhone() != null && !StringUtils.isEmpty(applyManager.getPhone())) {
			ApplyManagers exitApplyManager = applyManagersService.getOne(new QueryWrapper<ApplyManagers>().eq(ApplyManagers.COL_PHONE,applyManager.getPhone()));
			if(exitApplyManager == null){
				applyManager.setStatus(1);
				applyManager.setCreateTime(DateTime.now());
				applyManager.setUpdateTime(DateTime.now());
				applyManager.setValid(1);
				applyManagersService.save(applyManager);
				applyMsgUserService.pushMsg(applyManager.getName(), applyManager.getPhone(), applyManager.getCompanyName());
				return new Result(MessageCode.SUCCESS, "提交成功,稍候客服会与您联系", applyManager);
			}else{
				if(exitApplyManager.getStatus() == 1){
					return new Result(MessageCode.ERROR, "已提交申请, 请稍等");
				}else if(exitApplyManager.getStatus() == 2){
					return new Result(MessageCode.ERROR, "已注册");
				}else if(exitApplyManager.getStatus() == 0){
					return new Result(MessageCode.ERROR, "拒绝申请");
				}
			}
			return new Result(MessageCode.PARAM_ERROR, "提交失败");
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	/**
	 * 修改登录用户密码
	 */

	@ApiOperation(value = "修改密码", notes = "修改密码")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "password", value = "原始密码", dataType = "String",  required = true),
			@ApiImplicitParam(paramType = "query", name = "newPassword", value = "新密码", dataType = "String",   required = true)
	})
    @PostMapping("/resetPassword")
	@UseToken
	public Result resetPassword(String password, String newPassword){
		if(StringUtils.isEmpty(newPassword)){
			return new Result<SysUser>(MessageCode.PARAM_ERROR, "新密码不为能空");
		}
		SysUser manager = SecurityUtils.getLoginUser().getUser();
//		//原密码
//		password = ShiroUtils.sha256(password, manager.getSalt());
//		//新密码
//		newPassword = ShiroUtils.sha256(newPassword, manager.getSalt());

		//更新密码
		int flag = userService.resetUserPwd(manager.getUserName(),newPassword);
		if(flag <= 0){
			return new Result<SysUser>(MessageCode.PARAM_ERROR, "原密码不正确");
		}
		return new Result<SysUser>(MessageCode.SUCCESS, "修改成功");
	}


	@ApiOperation(value = "删除", notes = "删除")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = true)
	})
	@UseToken
	@Log(title = "删除合同")
	@PostMapping("/deleteContract")
	public Result<Boolean> delete(Long contractId) {
		if(contractId != null && contractId > 0) {
			boolean flag  = contractService.removeById(contractId);
			if(flag){
				return new Result<>(MessageCode.SUCCESS, "删除成功");
			}else{
				return new Result<>(MessageCode.ERROR, "删除失败");
			}
		}else {
			return new Result<>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "按合同名称查询合同", notes = "按合同名称查询合同")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "contractName", value = "合同名称", dataType = "String", required = true)
	})
	@UseToken
	@GetMapping("/queryByContractName")
	public Result<IPage<Contract>> queryByContractName(@ApiParam(hidden = true) Page<Contract> page, String contractName) {
		if(!StringUtils.isEmpty(contractName)) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			IPage<Contract> records  = contractService.queryByContractName(manager,page,contractName);
			return new Result<>(MessageCode.SUCCESS, "获取成功", records);
		}else {
			return new Result<>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@PostMapping("/upload")
	public Result<Map> testSend(@RequestParam("multipartFiles[]") List<MultipartFile> multipartFiles, @RequestParam("type") int type) {
		System.out.println("requestParam:"+multipartFiles.size());
		System.out.println("type:"+type);
		List<Map<String,String>> images = new ArrayList<>();
		for (MultipartFile multipartFile :  multipartFiles) {
			Map<String,String> params = new HashMap<>();
			String url = ossUtils.uploadFile(multipartFile);
			params.put("url",url);
			params.put("name",multipartFile.getOriginalFilename());
			images.add(params);
		}
		if(images.size() > 0){
			Map<String, Object> map = new HashMap<>();
			map.put("type",type);
			map.put("datumType",type);
			map.put("items",images);
			return new Result<Map>(MessageCode.SUCCESS, "上传成功", map);
		}else{
			Map<String, Object> map = new HashMap<>();
			map.put("type",type);
			map.put("datumType","");
			map.put("items",images);
			return new Result<Map>(MessageCode.ERROR, "上传失败", map);
		}
	}


	@ApiOperation(value = "添加合同资料", notes = "添加合同资料")
	@UseToken
	@Log(title = "添加合同资料")
	@PostMapping("/addContractDatum")
	public Result<Boolean> addOrUpdate( @RequestBody String contractDatumJson) {
		if(contractDatumJson != null && !StringUtils.isEmpty(contractDatumJson)) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Gson gson = new Gson();
            ContractDatumAppDto contractDatumDto = gson.fromJson(contractDatumJson, new TypeToken<ContractDatumAppDto>() {}.getType());
			if(contractDatumDto != null){
				if(contractDatumDto.getContractId() != null){
					Contract contract = contractService.getById(contractDatumDto.getContractId());
					if(contract != null){
						//更新文档资料上传状态
						contract.setDatumStatus(contractDatumDto.getUploadStatus());
						contractService.updateById(contract);
					}else{
						return new Result<Boolean>(MessageCode.PARAM_ERROR, "参数错误");
					}
				}else{
					return new Result<Boolean>(MessageCode.PARAM_ERROR, "参数错误");
				}
				List<ContractDatumAppDto.FileListBean> fileInfos = contractDatumDto.getFileList();
				if(fileInfos != null && fileInfos.size() > 0){
					Long contractId = contractDatumDto.getContractId();
					List<ContractDatum> contractDatumList = new ArrayList<>();
					for (ContractDatumAppDto.FileListBean fileInfo : fileInfos) {
                        for (ContractDatumAppDto.FileListBean.ItemsBean item : fileInfo.getItems()) {
                            ContractDatum contractDatum = new ContractDatum();
                            contractDatum.setFileName(item.getName());
                            if(FileUtils.isImage(item.getUrl())){
                                contractDatum.setType(1);//图片
                            }else{
                                contractDatum.setType(2);//文件
                            }
                            contractDatum.setOssFilePath(item.getUrl());
                            contractDatum.setStatus(1);
                            contractDatum.setContractId(contractDatumDto.getContractId());
                            contractDatum.setDatumType(fileInfo.getDatumType());
                            contractDatum.setRemark(contractDatumDto.getRemark());
                            contractDatum.setContractId(contractId);
                            contractDatum.setValid(1);
                            contractDatum.setCreateBy(manager.getUserId());
                            contractDatumList.add(contractDatum);
                        }
					}
					contractDatumService.saveBatch(contractDatumList);
				}
			}
			return new Result<Boolean>(MessageCode.SUCCESS, "上传成功",true);
		}else {
			return new Result<Boolean>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@ApiOperation(value = "是否是企业管理员(法人)", notes = "是否是企业管理员(法人)")
	@UseToken
	@Log(title = "是否是企业管理员(法人),根据账号查询是否是企业法人")
	@GetMapping("/isCompanyAdmin")
	public Result<Company> isCompanyAdmin() {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		if(manager != null && !StringUtils.isEmpty(manager.getMobile())) {
			QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
			companyQueryWrapper.eq(Company.COL_LEGAL_PERSON_MOBILE,manager.getMobile());
			Company company = companyService.getOne(companyQueryWrapper);
			if(company != null){
				return new Result<Company>(MessageCode.SUCCESS, "获取成功",company);
			}else{
				return new Result<Company>(MessageCode.SUCCESS, "获取失败",null);
			}

		}else {
			return new Result<Company>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

}
